package com.yuke.cloud.common.util.excel;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Enumeration;

/*
 * <p>Company: Copyright (c) 2018. yuke All Rights Reserved. </br> </p>
 * <p>Title：yuke-mall </br> </p>
 * <p>com.yuke.cloud.service.omc.utils Description TODO </br> </p>
 * @Author wg
 * @Date   2020/6/15 17:10
 */
public class RequestUtil {
    /**
     * request POST 参数转为JSON
     * @param request
     * @return
     */
    public static JSONObject postParm2Json(HttpServletRequest request){
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            StringBuilder builder = new StringBuilder("");
            String str = "";
            while ((str = reader.readLine()) != null) {
                builder.append(str);
            }
            JSONObject json = JSONObject.parseObject(builder.toString());
            return json;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * request GET 参数转为JSON
     * @param request
     * @return
     */
    public static JSONObject getParm2Json(HttpServletRequest request) {
        JSONObject requestJson = new JSONObject();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String[] pv = request.getParameterValues(paramName);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < pv.length; i++) {
                if (pv[i].length() > 0) {
                    if (i > 0) {
                        sb.append(",");
                    }
                    sb.append(pv[i]);
                }
            }
            requestJson.put(paramName, sb.toString());
        }
        return requestJson;
    }
}
